package com.chenzouquan.util.format;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.File;
import java.io.IOException;

public class JsonFormatter {
    public static void formatJsonFile(String jsonFilePath) {
        try {
            // 创建ObjectMapper对象
            ObjectMapper objectMapper = new ObjectMapper();

            // 启用格式化输出
            objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

            // 读取JSON文件内容
            Object jsonData = objectMapper.readValue(new File(jsonFilePath), Object.class);

            // 创建ObjectWriter对象
            ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();

            // 将格式化后的JSON内容写入JSON文件
            objectWriter.writeValue(new File(jsonFilePath), jsonData);

            System.out.println("JSON文件格式化成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

